﻿using System.Collections.Generic;
using System.IO;
using System.Text;
using GameFramework;
using Newtonsoft.Json;
using StarForce;
using UnityEditor;
using UnityEngine;

namespace Unity.Editor
{
    public static class GenLuaFilesHelp
    {
        private static string m_filesConfigFile = Application.dataPath + "/GameMain/Configs/LuaFilesConfig.json";
        
        [MenuItem("XLua/生成所有Lua文件信息配置LuaFilesConfig.json")]
        public static void GenerateLuaFilesConfig()
        {
            string rootPath =  Application.dataPath + "/GameMain/Lua/";;
            string suffix = ".lua.txt";

            List<string> m_fileList = new List<string>();
            CollectFilesWithSuffix(rootPath, suffix, ref m_fileList);
            StringBuilder sb = new StringBuilder();

            foreach (string file in m_fileList)
            {
                string path = Utility.Path.GetRegularPath(file);
                string luaName = path.Replace(rootPath,"").Replace(suffix,"");
                string json = JsonConvert.SerializeObject(new LuaFileInfo(luaName));
                //Debug.Log("json:" + json);
                sb.Append(json);

                sb.Append("\n");
            }
            File.WriteAllText(m_filesConfigFile, sb.ToString(), Encoding.UTF8);
            AssetDatabase.Refresh();
        }
        
        /// <summary>
        /// 收集指定目录下指定后缀名的所有文件
        /// </summary>
        /// <param name="rootPath"></param>
        /// <param name="suffix"></param>
        /// <param name="fileList"></param>
        public static void CollectFilesWithSuffix(string rootPath, string suffix, ref List<string> fileList)
        {
            string[] dirs = Directory.GetDirectories(rootPath);
            foreach (string path in dirs)
            {
                CollectFilesWithSuffix(path, suffix, ref fileList);
            }

            string[] files = Directory.GetFiles(rootPath);
            foreach (string filePath in files)
            {
                if (filePath.Substring(filePath.IndexOf(".")) == suffix)
                {
                    fileList.Add(filePath);
                }
            }
        }
    }
}